package com.zlll.winner.service.bbs.async;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlll.winner.business.model.bbs.BbsUserComment;
import com.zlll.winner.enums.bbs.ActionLogEnum;
import com.zlll.winner.mapper.bbs.BbsUserCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 评论异步服务实现类
 * </p>
 *
 * @author Walert
 * @since 2019-09-12
 */
@Service
@Async
@Slf4j
public class BbsCommentAsyncService {

    @Resource
    private BbsUserCommentMapper userCommentMapper;

    private int count(long commentId,Integer actionType){
        BbsUserComment bbsUserComment = userCommentMapper.selectById(commentId);
        BbsUserComment updateObj = new BbsUserComment();
        updateObj.setUpdateTime(System.currentTimeMillis());
        if(actionType == ActionLogEnum.ActionTypeEnum.LIKE.val()){
            updateObj.setLikeNum(bbsUserComment.getLikeNum()+1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.REPLY.val()){
            updateObj.setReplyNum(bbsUserComment.getReplyNum()+1);
        }else if(actionType == ActionLogEnum.ActionTypeEnum.UNLIKE.val()){
            updateObj.setLikeNum(bbsUserComment.getLikeNum()-1);
        }
        int update = userCommentMapper.update(updateObj,
                Wrappers.<BbsUserComment>lambdaQuery()
                        .eq(BbsUserComment::getId, commentId)
                        .eq(BbsUserComment::getUpdateTime, bbsUserComment.getUpdateTime()));
        return update;
    }


    @Async
    public void changeNumber(Long commentId,Integer actionType) throws InterruptedException {
        int res = 0;
        int sum = 10;
        while(res == 0 && sum > 0){
            res = count(commentId,actionType);
            if(res == 0 ) Thread.sleep(500L);
            sum --;
        }
        log.error("统计评论数量完毕。");
    }

}
